from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
from sqlalchemy.orm import sessionmaker, DeclarativeBase 
from typing import AsyncGenerator
from sqlalchemy import Column, Integer, DateTime, func

DATABASE_URL = "postgresql+asyncpg://chf:chenhaifeng@47.120.55.99/pg"

engine = create_async_engine(DATABASE_URL, echo=True)

async_session = sessionmaker(bind=engine, class_=AsyncSession, expire_on_commit=False)

async def get_db() -> AsyncGenerator[AsyncSession, None]:
    db = async_session()
    try:
        yield db
    finally:
        await db.close()

class Base(DeclarativeBase):
    version = Column(Integer, nullable=False, default=1, server_default="1", comment="版本号")
    created_at = Column(DateTime(timezone=True), nullable=False, default=func.now(), comment="创建时间")
    updated_at = Column(DateTime(timezone=True), nullable=False, default=func.now(), onupdate=func.now(), comment="更新时间")